using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Web.UI;

namespace OrbitOne.GoogleCustomSearch
{
   public class GoogleCustomSearch
   {
       #region Properties
       private RequestParameterBuilder parameterBuilder;


       public RequestParameterBuilder ParameterBuilder
       {
           get { return parameterBuilder; }
           set { parameterBuilder = value; }
       }
       #endregion Properties
       #region Constructor  
       public GoogleCustomSearch()
       {
           parameterBuilder = new RequestParameterBuilder();
       }
       #endregion Constructor

      

#region Methods
       
       private XmlDocument GetSearchResult()
       {


           string requestParameters = ParameterBuilder.Build();
           HttpWebRequest webRequest =
      (HttpWebRequest)WebRequest.Create(string.Format(@"http://www.google.com/search{0}",requestParameters));
           webRequest.Method = "GET";

           HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
           Stream newStream = webResponse.GetResponseStream();
           
           
           XmlDocument document  = new XmlDocument();
           document.Load(newStream);
           newStream.Close();
           return document;

           
       }


       public string TransformResultToHtml(string xsltPath)
       {
           XmlDocument searchResult = this.GetSearchResult();
           StringBuilder htmlText = new StringBuilder();
           HtmlTextWriter output = new HtmlTextWriter(new StringWriter(htmlText));
           
           try
           {


               XPathDocument myXPathDoc = new XPathDocument(new XmlNodeReader(searchResult));
               XslCompiledTransform myXslTrans = new XslCompiledTransform();
               myXslTrans.Load(xsltPath);
              
               
               myXslTrans.Transform(myXPathDoc, null, output);


           }
           catch (Exception e)
           {

              //Todo: log error
               throw e;
           }
           return htmlText.ToString();
       }
       #endregion Methods


   }
}
